/**
 * @file LogStream.h
 * @brief 日志流式接口，提供高效的格式化功能
 * @author Enterprise Logger Team
 * @date 2024
 */

#ifndef LOGGER_LOGSTREAM_H
#define LOGGER_LOGSTREAM_H

#include <cstring>
#include <string>
#include <algorithm>
#include <limits>
#include <cstdint>
#include <type_traits>
#include <vector>
#include <sstream>

namespace logger {

namespace detail {
    const int kSmallBufferSize = 4000;  // 4KB - 适合栈上分配
    const int kLargeBufferSize = 4000 * 1000;  // 4MB - 用于异步日志缓冲

    /**
     * @brief 固定大小缓冲区模板
     * @tparam SIZE 缓冲区大小
     */
    template<int SIZE>
    class FixedBuffer {
    public:
        FixedBuffer() : cur_(data_) {}
        ~FixedBuffer() = default;

        // 禁用拷贝
        FixedBuffer(const FixedBuffer&) = delete;
        FixedBuffer& operator=(const FixedBuffer&) = delete;

        // 添加数据到缓冲区
        void append(const char* buf, size_t len) {
            if (static_cast<size_t>(avail()) > len) {
                memcpy(cur_, buf, len);
                cur_ += len;
            }
        }

        // 获取数据指针
        const char* data() const { return data_; }
        int length() const { return static_cast<int>(cur_ - data_); }

        // 当前写入位置
        char* current() { return cur_; }
        int avail() const { return static_cast<int>(end() - cur_); }
        void add(size_t len) { cur_ += len; }

        // 重置缓冲区
        void reset() { cur_ = data_; }
        void bzero() { memset(data_, 0, sizeof(data_)); }

        // 转换为字符串
        std::string toString() const { return std::string(data_, length()); }

    private:
        const char* end() const { return data_ + sizeof(data_); }

        char data_[SIZE];
        char* cur_;
    };
}

/**
 * @brief 智能格式化参数容器
 */
class FormatArg {
public:
    template<typename T>
    FormatArg(const T& value) : data_(toString(value)) {}
    
    const std::string& str() const { return data_; }
    
private:
    template<typename T>
    std::string toString(const T& value) {
        if constexpr (std::is_same_v<T, std::string>) {
            return value;
        } else if constexpr (std::is_same_v<T, const char*>) {
            return std::string(value ? value : "(null)");
        } else if constexpr (std::is_arithmetic_v<T>) {
            return std::to_string(value);
        } else {
            // 对于其他类型，尝试转换为字符串
            std::ostringstream oss;
            oss << value;
            return oss.str();
        }
    }
    
    std::string data_;
};

/**
 * @brief 日志流类，提供operator<<重载和智能格式化功能
 */
class LogStream {
public:
    typedef detail::FixedBuffer<detail::kSmallBufferSize> Buffer;

    LogStream() = default;
    ~LogStream() = default;
    
    // 智能格式化状态
    enum class FormatState {
        NORMAL,      // 普通模式
        FORMATTING   // 格式化模式
    };
    
private:
    FormatState format_state_ = FormatState::NORMAL;
    std::string format_template_;  // 格式化模板
    std::vector<FormatArg> format_args_;  // 收集的参数
    size_t expected_args_ = 0;  // 期望的参数数量
    
    // 计算格式字符串中{}的数量
    size_t countPlaceholders(const std::string& str) {
        size_t count = 0;
        size_t pos = 0;
        while ((pos = str.find("{}", pos)) != std::string::npos) {
            ++count;
            pos += 2;
        }
        return count;
    }
    
    // 执行格式化替换
    std::string formatString() {
        std::string result = format_template_;
        for (const auto& arg : format_args_) {
            size_t pos = result.find("{}");
            if (pos != std::string::npos) {
                result.replace(pos, 2, arg.str());
            }
        }
        return result;
    }
    
    // 重置格式化状态
    void resetFormatState() {
        format_state_ = FormatState::NORMAL;
        format_template_.clear();
        format_args_.clear();
        expected_args_ = 0;
    }
    
    // 检查是否应该输出格式化结果
    void checkAndFlushFormat() {
        if (format_state_ == FormatState::FORMATTING && 
            format_args_.size() >= expected_args_) {
            std::string formatted = formatString();
            buffer_.append(formatted.c_str(), formatted.size());
            resetFormatState();
        }
    }
    
public:

    // 基本类型支持
    LogStream& operator<<(bool v) {
        if (format_state_ == FormatState::FORMATTING) {
            format_args_.emplace_back(v);
            checkAndFlushFormat();
        } else {
            buffer_.append(v ? "true" : "false", v ? 4 : 5);
        }
        return *this;
    }

    LogStream& operator<<(short v) {
        return operator<<(static_cast<int>(v));
    }

    LogStream& operator<<(unsigned short v) {
        return operator<<(static_cast<unsigned int>(v));
    }

    LogStream& operator<<(int v) {
        if (format_state_ == FormatState::FORMATTING) {
            format_args_.emplace_back(v);
            checkAndFlushFormat();
        } else {
            formatInteger(v);
        }
        return *this;
    }

    LogStream& operator<<(unsigned int v) {
        if (format_state_ == FormatState::FORMATTING) {
            format_args_.emplace_back(v);
            checkAndFlushFormat();
        } else {
            formatInteger(v);
        }
        return *this;
    }

    LogStream& operator<<(long v) {
        if (format_state_ == FormatState::FORMATTING) {
            format_args_.emplace_back(v);
            checkAndFlushFormat();
        } else {
            formatInteger(v);
        }
        return *this;
    }

    LogStream& operator<<(unsigned long v) {
        if (format_state_ == FormatState::FORMATTING) {
            format_args_.emplace_back(v);
            checkAndFlushFormat();
        } else {
            formatInteger(v);
        }
        return *this;
    }

    LogStream& operator<<(long long v) {
        if (format_state_ == FormatState::FORMATTING) {
            format_args_.emplace_back(v);
            checkAndFlushFormat();
        } else {
            formatInteger(v);
        }
        return *this;
    }

    LogStream& operator<<(unsigned long long v) {
        if (format_state_ == FormatState::FORMATTING) {
            format_args_.emplace_back(v);
            checkAndFlushFormat();
        } else {
            formatInteger(v);
        }
        return *this;
    }

    LogStream& operator<<(float v) {
        if (format_state_ == FormatState::FORMATTING) {
            format_args_.emplace_back(v);
            checkAndFlushFormat();
        } else {
            return operator<<(static_cast<double>(v));
        }
        return *this;
    }

    LogStream& operator<<(double v);

    LogStream& operator<<(char v) {
        if (format_state_ == FormatState::FORMATTING) {
            format_args_.emplace_back(std::string(1, v));
            checkAndFlushFormat();
        } else {
            buffer_.append(&v, 1);
        }
        return *this;
    }

    LogStream& operator<<(const char* str) {
        if (!str) str = "(null)";
        
        std::string temp(str);
        return operator<<(temp);  // 复用string版本的逻辑
    }

    LogStream& operator<<(const unsigned char* str) {
        return operator<<(reinterpret_cast<const char*>(str));
    }

    LogStream& operator<<(const std::string& v) {
        // 检查是否包含格式化占位符
        size_t placeholder_count = countPlaceholders(v);
        if (placeholder_count > 0 && format_state_ == FormatState::NORMAL) {
            // 进入格式化模式
            format_state_ = FormatState::FORMATTING;
            format_template_ = v;
            expected_args_ = placeholder_count;
            format_args_.clear();
            
            // 如果没有占位符需要填充，直接输出
            if (expected_args_ == 0) {
                buffer_.append(v.c_str(), v.size());
                resetFormatState();
            }
        } else if (format_state_ == FormatState::FORMATTING) {
            // 已经在格式化模式，这是一个参数
            format_args_.emplace_back(v);
            checkAndFlushFormat();
        } else {
            // 普通字符串，直接输出
            buffer_.append(v.c_str(), v.size());
        }
        return *this;
    }

    // 指针类型
    LogStream& operator<<(const void* p);
    
    // nullptr类型特化
    LogStream& operator<<(std::nullptr_t) {
        buffer_.append("nullptr", 7);
        return *this;
    }

    // 通用类型支持（需要实现operator<<）
    template<typename T>
    typename std::enable_if<
        std::is_class<T>::value && !std::is_same<T, std::string>::value,
        LogStream&
    >::type
    operator<<(const T& v) {
        if (format_state_ == FormatState::FORMATTING) {
            format_args_.emplace_back(v);
            checkAndFlushFormat();
        } else {
            // 使用临时stringstream转换
            std::string temp = formatObject(v);
            buffer_.append(temp.c_str(), temp.size());
        }
        return *this;
    }

    void append(const char* data, int len) {
        buffer_.append(data, len);
    }

    const Buffer& buffer() const { return buffer_; }
    void resetBuffer() { buffer_.reset(); }

private:
    // 整数格式化（高效实现）
    template<typename T>
    void formatInteger(T v) {
        if (buffer_.avail() >= kMaxNumericSize) {
            size_t len = convert(buffer_.current(), v);
            buffer_.add(len);
        }
    }

    // 数字转字符串（优化版本）
    template<typename T>
    size_t convert(char* buf, T value) {
        const char digits[] = "9876543210123456789";
        const char* zero = digits + 9;
        static_assert(sizeof(digits) == 20, "wrong digits");

        T i = value;
        char* p = buf;

        do {
            int lsd = static_cast<int>(i % 10);
            i /= 10;
            *p++ = zero[lsd];
        } while (i != 0);

        if (value < 0) {
            *p++ = '-';
        }
        *p = '\0';
        std::reverse(buf, p);

        return p - buf;
    }

    // 辅助函数：格式化对象
    template<typename T>
    std::string formatObject(const T& v) {
        // 简单实现，实际使用时应该优化
        char buf[256];
        snprintf(buf, sizeof(buf), "%p", &v);
        return std::string(buf);
    }

    // 辅助函数：十六进制转换
    size_t convertHex(char* buf, uintptr_t value);

    Buffer buffer_;
    static const int kMaxNumericSize = 32;
};

// 格式化类，用于格式化输出
class Fmt {
public:
    template<typename T>
    Fmt(const char* fmt, T val);

    const char* data() const { return buf_; }
    int length() const { return length_; }

private:
    char buf_[32];
    int length_;
};

}  // namespace logger

#endif  // LOGGER_LOGSTREAM_H
